﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace HeritageAcademy.Library.Controls
{
	/// <summary>
	/// Quotes scroll class.
	/// </summary>
	public partial class QuotesScroll
    {
        #region Parameters

        private int currentQuoteNumber;
        private int totalQuoteNumber;
        private readonly DispatcherTimer dTimer;

        #endregion

        #region Ctor

        public QuotesScroll()
		{
			InitializeComponent();

            currentQuoteNumber = 0;
            NaturalNumberSelector.SelectorChangedValueUp += NaturalNumberSelector_SelectorChangedValueUp;
            NaturalNumberSelector.SelectorChangedValueDown += NaturalNumberSelector_SelectorChangedValueDown;

            // [I] - timer realization
            //System.Threading.TimerCallback tc = new System.Threading.TimerCallback(OnTimerCallback);
            //System.Threading.Timer objTimer = new System.Threading.Timer(tc);
            //objTimer.Change(0, 8000);

            // [II] - timer realization
            dTimer = new DispatcherTimer();
            dTimer.Tick += dispatcherTimer_Tick;
		}

        #endregion

        #region Public Methods

        /// <summary>
        /// Set initial state of parameters and start timer.
        /// </summary>
        /// <param name="interval">Update interval in seconds</param>
        public void StartAutoScrolling(int interval)
        {
            // set total number
            totalQuoteNumber = spQuotes.Children.Count;
            nnsNumber.MaxValue = totalQuoteNumber;
            nnsNumber.MinValue = 1;
            // show first quotation
            spQuotes.Children[0].Opacity = 1.0;
            spQuotes.Children[0].Visibility = Visibility.Visible;
            // start timer
            dTimer.Interval = TimeSpan.FromMilliseconds(interval * 1000);
            dTimer.Start();
        }

        /*
        // [I] - need this for timer realization
        void OnTimerCallback(Object obj)
        {
            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        (System.Threading.ThreadStart)delegate()

             {
                    ScrollForward();
             });
        }
        */

        public void Add(string text)
        {
            var quote = new TextBlock
                            {
                                Text = text,
                                FontSize = 14.0,
                                Opacity = 0.0,
                                Visibility = Visibility.Collapsed,
                                TextWrapping = TextWrapping.Wrap
                            };

            spQuotes.Children.Add(quote);
        }

        public void Clear()
        {
            spQuotes.Children.Clear();
        }

        #endregion

        #region Private Methods

        private void PlayAnimation(UIElement hideElement, UIElement showElement)
        {
            var hide = FindResource("HideQuote") as Storyboard;
            EventHandler handler = null;
            handler = delegate(object s, EventArgs sbe)
            {
                if (hide != null) hide.Completed -= handler;
                var show = FindResource("ShowQuote") as Storyboard;
                if ( show != null ) show.Begin((FrameworkElement)showElement);
            };

            if (hide == null) return;
            hide.Completed += handler;
            hide.Begin((FrameworkElement)hideElement);
        }

        private void ScrollForward()
        {       
            if (currentQuoteNumber == totalQuoteNumber - 1)
            {
                PlayAnimation(spQuotes.Children[currentQuoteNumber], spQuotes.Children[0]);
                currentQuoteNumber = 0;
            }
            else
            {
                PlayAnimation(spQuotes.Children[currentQuoteNumber], spQuotes.Children[++currentQuoteNumber]);
            }

            nnsNumber.CurrentValue = currentQuoteNumber + 1;
        }

        private void ScrollBack()
        {
            if (currentQuoteNumber == 0)
            {
                PlayAnimation(spQuotes.Children[currentQuoteNumber], spQuotes.Children[spQuotes.Children.Count - 1]);
                currentQuoteNumber = totalQuoteNumber - 1;
            }
            else
            {
                PlayAnimation(spQuotes.Children[currentQuoteNumber], spQuotes.Children[--currentQuoteNumber]);

            }

            nnsNumber.CurrentValue = currentQuoteNumber + 1;
        }

        #endregion

        #region Event Handlers

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            ScrollForward();
        }

        void NaturalNumberSelector_SelectorChangedValueDown(object sender, EventArgs e)
        {
            dTimer.Stop();
            ScrollBack();
            dTimer.Start();
        }

        void NaturalNumberSelector_SelectorChangedValueUp(object sender, EventArgs e)
        {
            dTimer.Stop();
            ScrollForward();
            dTimer.Start();
        }

        #endregion
    }
}